package baidu.com.matedemo;

import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.baidu.duer.smartmate.out.DuerDevice;
import com.baidu.duer.smartmate.out.DuerSDK;
import com.baidu.duer.smartmate.out.WebType;
import com.baidu.duer.smartmate.web.ui.WebViewFragment;

import baidu.com.matedemo.base.BaseActivity;

/**
 * Created by niufei01 on 2017/12/12.
 */

public class SinglePageActivity extends BaseActivity {
    WebViewFragment webViewFragment = null;

    @Override
    public void onContentViewCreated(View view) {
        super.onContentViewCreated(view);

        WebType type = (WebType) getIntent().getSerializableExtra(DemoConstant.TYPE);
        if (WebType.SMARTHOME.equals(type)) {
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this);
        } else if (WebType.SKILLSTORE.equals(type)) {
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this);
        } else if (WebType.RESOURCE_ACCOUNT.equals(type)) {
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this);
        } else if (WebType.UNICAST.equals(type)) {
            // 该DuerDevice需要确保是已连接、链路已verify的状态，才支持在有声H5中点播音频
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this, DemoApp.getInstance().getCurreDuerDevice());
        } else if (WebType.ORDER_CENTER.equals(type)) {
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this, DemoApp.getInstance().getCurreDuerDevice());
        } else if (WebType.CHAT_FLOW.equals(type)) {
            DuerDevice duerDevice = DemoApp.getInstance().getCurreDuerDevice();
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this, duerDevice);
        } else if (WebType.XIAODU_WHISPER.equals(type)) {
            webViewFragment = DuerSDK.getDuerWebViewFragment(type, this);
        }

        if (webViewFragment == null) {
            return;
        }

        FragmentTransaction trans = this.getSupportFragmentManager().beginTransaction();
        trans.replace(R.id.common_layout, webViewFragment);
        trans.commitAllowingStateLoss();
        trans.show(webViewFragment);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && webViewFragment != null) {
            if (webViewFragment.canGoBack()) {
                webViewFragment.goBack();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (webViewFragment != null) {
            webViewFragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
